/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { ObjInfo, pickedFaceData, pickedLineData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

type FormDataType = {
  curve1: pickedLineData;
  curve2: pickedLineData;
  plane: pickedFaceData;
  radius: number;
};

type Params = {
  curve1: string;
  curve2: string;
  plane: string;
  radius: number;
};

function CommandFillet({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    curve1: undefined,
    curve2: undefined,
    plane: undefined,
    radius: 1,
  };
  const { picker } = useTools();

  const [formData, setFormData] = useState<FormDataType>(initData);

  const execute = async (preview: boolean) => {
    const { curve1, curve2, plane, radius } = formData;

    const params: Params = {
      curve1: curve1.edgeId,
      curve2: curve2.edgeId,
      plane: plane.meshId,
      radius,
    };

    await confirmCommand({ type: 'Fillet', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    } else {
      const params: Params = props.params;
      const { curve1, curve2, plane, radius } = params;

      await initEditDependency([curve1, curve2, plane]);

      setFormData({
        curve1: picker.generatePickObjByPickID(curve1) as pickedLineData,
        curve2: picker.generatePickObjByPickID(curve2) as pickedLineData,
        plane: picker.generatePickObjByPickID(plane) as pickedFaceData,
        radius: radius,
      });
    }
  }, []);

  const checkAndFinishDraw = async () => {
    const { radius } = formData;

    if (radius === 0) {
      MessageTip.error('半径不能为0');
    }

    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const isFormDataValid = () => {
    const { curve1, curve2, plane, radius } = formData;

    return (
      curve1 != null &&
      curve2 != null &&
      plane != null &&
      radius != null &&
      radius != 0
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-fillet', {
      commandName: 'CreateCurve',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve1: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      curve2: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickSurface,
      },
      radius: {
        type: 'number',
        title: '半径',
        format: NumberInputFormat.Length,
      },
    },
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      submitLoading={isLoading}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        curve1: {
          'ui:placeholder': '请输入曲面上的曲线1',
          'ui:autofocus': true,
        },
        curve2: {
          'ui:placeholder': '请输入曲面上的曲线2',
        },
        plane: {
          'ui:placeholder': '请输入曲面',
        },
        radius: {
          'ui:placeholder': '请输入半径',
        },
      }}
      submitText='完成'
      isFormDataValid={isFormDataValid()}
      onSubmit={checkAndFinishDraw}
    />
  );
}

export const cmdFillet: CurvedBaseCommand = {
  id: 'CmdFillet',
  label: 'command.fillet',
  icon: 'commands/curved/fillet',
  create: (label: string, onClose: () => void, props: ObjInfo) => (
    <CommandFillet
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
